import { DataTypes, Model, Optional } from 'sequelize';
import sequelize from '../utils/database';

// 定义Brand属性接口
export interface BrandAttributes {
  id: number;
  name: string;
  logo?: string;
  description?: string;
  website?: string;
  sortOrder: number;
  isShow: number;
  createdAt?: Date;
  updatedAt?: Date;
}

// 定义创建Brand时的可选属性
interface BrandCreationAttributes extends Optional<BrandAttributes, 'id' | 'createdAt' | 'updatedAt'> {}

// 定义Brand模型类
class Brand extends Model<BrandAttributes, BrandCreationAttributes> implements BrandAttributes {
  public id!: number;
  public name!: string;
  public logo?: string;
  public description?: string;
  public website?: string;
  public sortOrder!: number;
  public isShow!: number;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  // 实例方法：获取显示状态文本
  public getShowStatusText(): string {
    return this.isShow === 1 ? '显示' : '隐藏';
  }

  // 实例方法：获取完整品牌名称
  public getFullName(): string {
    return this.name;
  }

  // 实例方法：检查是否有Logo
  public hasLogo(): boolean {
    return !!this.logo;
  }
}

// 初始化Brand模型
Brand.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
      comment: '品牌ID'
    },
    name: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '品牌名称'
    },
    logo: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: '品牌Logo图片URL'
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '品牌描述'
    },
    website: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: '官方网站'
    },
    sortOrder: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '排序权重，数字越小越靠前'
    },
    isShow: {
      type: DataTypes.TINYINT,
      allowNull: false,
      defaultValue: 1,
      comment: '是否显示：1-显示，0-隐藏'
    }
  },
  {
    sequelize,
    tableName: 'brands',
    modelName: 'Brand',
    timestamps: true,
    paranoid: false,
    comment: '商品品牌表',
    indexes: [
      {
        name: 'idx_brand_name',
        fields: ['name']
      },
      {
        name: 'idx_brand_sort_order',
        fields: ['sortOrder']
      },
      {
        name: 'idx_brand_is_show',
        fields: ['isShow']
      }
    ]
  }
);

export default Brand;